'''
Created on Jun 4, 2010

@author: roni
'''
from flowDetails import FlowDetails

class Ns2Observations(object):
    '''
    Class that represents the observations recieved from an Ns2 simulation
    '''

    def __init__(self,flow_to_details = dict()):
        self.flow_to_details = flow_to_details
        
    def __getitem__(self,flow):
        return self.flow_to_details[flow]
    def __setitem__(self,flow, details):
        self.flow_to_details[flow]=details
    def __eq__(self,obj):
        return self.flow_to_details==obj.flow_to_details
    
    def is_equal(self,obj):
        if set(self.flow_to_details.keys())!=set(obj.flow_to_details.keys()):
            return False
        for flow in self.flow_to_details:
            details = self.flow_to_details[flow]
            obj_details = obj.flow_to_details[flow]
            if details.__eq__(obj_details)==False:
                return False
        return True
            
  
    def save_flow_details(self,out_file,flow_details):
        ''' Write the flow details to a file '''
        out_file.write("%s,%s,%s,%s,%s\n" % (flow_details.flow_id,flow_details.source,flow_details.target,flow_details.delay,flow_details.packet_count))
        for node in flow_details.path:
            out_file.write("%s," % node)
        out_file.write("\n")
    
    def load_flow_details(self,in_file):                
        line = in_file.readline()
        if len(line)==0:
            return None
        parts = line.split(",")
        flow_id = int(parts[0].strip())
        source = int(parts[1].strip())
        target = int(parts[2].strip())
        delay = float(parts[3].strip())
        packet_count = int(parts[4].strip())
        
        line = in_file.readline()
        parts = line.split(",")
        path = []
        for part in parts:
            part = part.strip()
            if len(part)>0: # Excluding end-of-line part (due to extra comma at the end of the line)            
                path.append(int(part.strip()))
            
    
        flow_details = FlowDetails(flow_id, source, target)
        flow_details.delay = delay
        flow_details.packet_count = packet_count
        flow_details.path = path
        return flow_details
    
    
    def save(self,file_name):        
        out_file = file(file_name,'w')
        for details in self.flow_to_details.values():
            self.save_flow_details(out_file, details)
        out_file.close()
        
    def load(self,file_name):
        in_file = file(file_name,'r')
        self.flow_to_details.clear()
        flow_details = self.load_flow_details(in_file)
        while flow_details is not None:
            self.flow_to_details[flow_details.flow_id]=flow_details
            flow_details = self.load_flow_details(in_file)
        
        
        